﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;

namespace HHPS.CreditEducation.Frameworks.Commons
{
    public static class Utils
    {
        public static void UpdateProperties<T>(T orginal, ref T dest, params string[] skips) where T : class
        {
            Type destType = dest.GetType();
            PropertyInfo[] destPropertyInfos =
                destType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            Type orginalType = orginal.GetType();
            PropertyInfo[] orginalPropertyInfos =
                orginalType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo destInfo in destPropertyInfos)
            {
                string propertyName = destInfo.Name;
                if (skips.Contains(propertyName)) continue;

                PropertyInfo orgInfo = GetValue(propertyName, orginalPropertyInfos);
                if (destInfo.CanWrite && orgInfo.CanRead)
                {
                    destInfo.SetValue(dest, orgInfo.GetValue(orginal, null), null);
                }
            }
        }

        private static PropertyInfo GetValue(string propertyName, IEnumerable<PropertyInfo> propertyInfos)
        {
            return propertyInfos.FirstOrDefault(info => info.Name == propertyName);
        }

        public static Image ByteArrayToImage(byte[] byteArrayIn)
        {
            var ms = new MemoryStream(byteArrayIn);
            Image returnImage = Image.FromStream(ms);
            return returnImage;
        }

        public static byte[] ImageToByteArray(Image imageIn)
        {
            var ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
    }
}